package com.hoan.component.kotlin

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.util.Log
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.hoan.component.kotlin.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.time.LocalTime
import java.time.format.DateTimeFormatter


/**
 *
 *
 * @author chenqiang
 * @date  2024/4/13
 */
class MainActivity : AppCompatActivity() {
    companion object {
        var TAG = "MainActivity"
    }

    private val liveData = MutableLiveData<Int>()

    var inputWords = ""

    //定制化
    private lateinit var bitmapOrigin: Bitmap
    private lateinit var bitmapIcon: Bitmap
    private lateinit var bitmapIcon1: Bitmap
    private lateinit var bitmapIcon2: Bitmap

    //图片水印
    val lengthFix = ConvertUtils.dp2px(40f)

    //绘制文字
    val textOff = ConvertUtils.dp2px(15f)

    //位置坐标
    var positionRatioX: Float = ConvertUtils.dp2px(150f).toFloat()
    var positionRatioY: Float = ConvertUtils.dp2px(30f).toFloat()
    var sizeRatioWidth: Float = ConvertUtils.dp2px(90f).toFloat()
    var sizeRatioHeight: Float = ConvertUtils.dp2px(120f).toFloat()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        positionRatioX.let {

        }

        positionRatioX.run {

        }

        positionRatioX.also {

        }

        binding.tvPop.setOnClickListener {
//            startActivity(Intent(this@MainActivity, PopActivity::class.java))
            GlobalScope.launch(Dispatchers.Main) {
                "getUserInfo before".log()
                val user = getUserInfo()
                "getUserInfo after".log()
                user.log()

                "getFriendList before".log()
                val friendList = getFriendList(user)
                "getFriendList after".log()
                friendList.log()

                "getFeedList before".log()
                val feedList = getFeedList(friendList)
                "getFeedList after".log()
                feedList.log()
            }
        }


        binding.tvOperate.setOnClickListener {
            for (i in 0..2) {
                Log.e(TAG, "setValue: $i")
                liveData.value = i
//                Log.e(TAG, "postValue: $i")
//            liveData.postValue(i)
            }
        }

        for (i in 0..3) {
            Log.e(TAG, "setValue: $i")
            liveData.value = i
//            Log.e(TAG, "postValue: $i")
//            liveData.postValue(i)
        }

        // 订阅观察者
        liveData.observe(this) {
            Log.e(TAG, "observer: $it")
        }

        val bitmapOriginUrl =
            "https://img1.baidu.com/it/u=1627161978,3490425294&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500"
//            "https://uat-us-cdn.obuy.com/image/gift-card-io8mxg.png.png"

        GlobalScope.launch(Dispatchers.Main) {
            bitmapOrigin = withContext(Dispatchers.IO) {
                Glide.with(this@MainActivity)
                    .asBitmap()
                    .load(bitmapOriginUrl)
                    .submit()
                    .get()
            }
            bitmap2Svg(bitmapOrigin)
            binding.ivPic.setImageBitmap(bitmapOrigin)
        }


        GlobalScope.launch(Dispatchers.Main) {
            bitmapIcon1 = withContext(Dispatchers.IO) {
                Glide.with(this@MainActivity)
                    .asBitmap()
                    .load("https://img2.baidu.com/it/u=3688307269,1255378263&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=833")
                    .submit()
                    .get()
            }
            binding.pic1.setImageBitmap(bitmapIcon1)
            bitmapIcon = bitmapIcon1
        }

        binding.pic1.setOnClickListener {
            bitmapIcon = bitmapIcon1
            val bitmapTemp = drawTextImage(
                bitmapIcon = bitmapIcon,
                words = inputWords
            )

//            bitmapToBase64(bitmapTemp)

            bitmap2Svg(bitmapTemp)
            binding.ivPic.setImageBitmap(bitmapTemp)
        }

        GlobalScope.launch(Dispatchers.Main) {
            bitmapIcon2 = withContext(Dispatchers.IO) {
                Glide.with(this@MainActivity)
                    .asBitmap()
                    .load("https://img2.baidu.com/it/u=2098123959,443507525&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889")
                    .submit()
                    .get()
            }
            binding.pic2.setImageBitmap(bitmapIcon2)
        }

        binding.pic2.setOnClickListener {
            bitmapIcon = bitmapIcon2
            val bitmapTemp = drawTextImage(
                bitmapIcon = bitmapIcon2,
                words = inputWords
            )
//            bitmapToBase64(bitmapTemp)

            bitmap2Svg(bitmapTemp)

            binding.ivPic.setImageBitmap(bitmapTemp)

        }


        binding.etInput.apply {
            addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }

                override fun afterTextChanged(s: Editable?) {
                    inputWords = s.toString()

                    val bitmapTemp = drawTextImage(
                        bitmapIcon = bitmapIcon,
                        words = inputWords
                    )
                    binding.ivPic.setImageBitmap(bitmapTemp)
                }
            })
        }


        binding.tvClear.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                words = "去除水印"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }

        binding.tvFont1.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 1,
                words = "ABC1"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
        binding.tvFont2.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 2,
                words = "ABC2"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
        binding.tvFont3.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 3,
                words = "ABC3"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
        binding.tvFont4.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 4,
                words = "ABC4"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
        binding.tvFont5.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 5,
                words = "ABC5"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
        binding.tvFont6.setOnClickListener {
            val bitmapTemp = drawTextImage(
                bitmapIcon = null,
                fontType = 6,
                words = "ABC6"
            )
            binding.ivPic.setImageBitmap(bitmapTemp)
        }
    }

    private fun drawTextImage(
        bitmapIcon: Bitmap? = null,
        fontType: Int? = 0,
        words: String? = null
    ): Bitmap {
        //画笔
        val paint = Paint()
        /*.apply {
        color = Color.BLACK
        textSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            10f, resources.displayMetrics
        )
    }*/
        paint.setColor(Color.BLACK)
        paint.textSize =
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10f, resources.displayMetrics)
        paint.typeface = when (fontType) {
            0 -> {
                Typeface.createFromAsset(assets, "fonts/Basalte.ttf")
            }

            1 -> {
                Typeface.createFromAsset(assets, "fonts/DancingScript.otf")
            }

            2 -> {
                Typeface.createFromAsset(assets, "fonts/GL.otf")
            }

            3 -> {
                Typeface.createFromAsset(assets, "fonts/HankenGrotesk.ttf")
            }

            4 -> {
                Typeface.createFromAsset(assets, "fonts/MadimiOne.otf")
            }

            5 -> {
                Typeface.createFromAsset(assets, "fonts/TurretRoad.ttf")
            }

            else -> {
                Typeface.createFromAsset(assets, "fonts/Basalte.ttf")
            }
        }

        //绘制背景
        val bitmapBg = Bitmap.createBitmap(
            bitmapOrigin,
            0,
            0,
            bitmapOrigin.width,
            bitmapOrigin.height,
            null,
            true
        )
        val canvas = Canvas(bitmapBg)
//        paint.setColor(resources.getColor(R.color.white))
//        canvas.drawBitmap(bitmapOrigin, 0f, 0f, paint)

        //绘制矩形
        paint.setColor(resources.getColor(R.color.red))
//        paint.setColor(Color.TRANSPARENT)
        val rect = Rect(
            positionRatioX.toInt(),
            positionRatioY.toInt(),
            (positionRatioX + sizeRatioWidth).toInt(),
            (positionRatioY + sizeRatioHeight).toInt()
        )
        canvas.drawRect(rect, paint)

        val rectWord = Rect()
        paint.getTextBounds(words, 0, words?.length ?: 0, rectWord)
        var widthWord = paint.measureText(words)
        val heightWord = rectWord.height()

        while (widthWord >= sizeRatioWidth) {
            paint.textSize -= 1
            widthWord = paint.measureText(words)
        }

        //绘制水印图片
        if (bitmapIcon == null) {
            //绘制文字
            paint.setColor(resources.getColor(R.color.white))
            canvas.drawText(
                words ?: "",
                positionRatioX,
                positionRatioY + heightWord,
                paint
            )

        } else {
            //绘制文字
            paint.setColor(resources.getColor(R.color.white))
            canvas.drawText(
                words ?: "",
                positionRatioX,
                positionRatioY + lengthFix + heightWord,
                paint
            )

            val widthIcon = bitmapIcon.width
            val heightIcon = bitmapIcon.height

            val scaleX = if (widthIcon > lengthFix) lengthFix.toFloat() / widthIcon else 1f
            val scaleY = if (heightIcon > lengthFix) lengthFix.toFloat() / heightIcon else 1f
            val matrix = Matrix().apply {
                postScale(scaleX, scaleY)
            }

            val bitmapTemp =
                Bitmap.createBitmap(bitmapIcon, 0, 0, widthIcon, heightIcon, matrix, true)
            canvas.drawBitmap(
                bitmapTemp,
                positionRatioX,
                positionRatioY,
                paint
            )

            /*val bitmapTemp = Bitmap.createBitmap(lengthFix, lengthFix,Bitmap.Config.ARGB_8888)
            canvas.setBitmap(bitmapTemp)
            val scaleX = lengthFix / widthIcon
            val scaleY = lengthFix / heightIcon
            canvas.drawBitmap(
                bitmapIcon,
                positionRatioX,
                positionRatioY,
                paint
            )*/
        }

        return bitmapBg
    }

    private fun bitmapToBase64(bitmap: Bitmap): String {
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
        val byteArray = byteArrayOutputStream.toByteArray()
        val temp = Base64.encodeToString(byteArray, Base64.DEFAULT)
        LogUtils.eTag("MainActivity", "temp $temp")
        return temp
    }

    private fun bitmap2Svg(bitmap: Bitmap) {
        val width: Int = bitmap.getWidth()
        val height: Int = bitmap.getHeight()
        LogUtils.eTag("MainActivity", "width $width height $height")

        // 创建一个简单的SVG字符串
        /*val svgBuilder = StringBuilder()
        svgBuilder
            .append("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"")
            .append(width)
            .append("\" height=\"")
            .append(height)
            .append("\">\n")
        svgBuilder
            .append("  <rect x=\"0\" y=\"0\" width=\"")
            .append(width)
            .append("\" height=\"")
            .append(height)
            .append("\" fill=\"none\" stroke=\"black\"/>\n")
        svgBuilder.append("</svg>")*/


        // 创建一个简单的SVG字符串
        /* val svgBuilder = StringBuilder()
         svgBuilder
             .append("<svg xmlns=\"http://www.w3.org/2000/svg\"")
             .append(" \"xmlns:xlink=\"http://www.w3.org/1999/xlink\"")
             .append(" \"version=1.1\"")
             .append("\">\n")

         svgBuilder
             .append("  <image width=\"")
             .append(450)
             .append("\" height=\"")
             .append(250)
             .append(" \"xlink:href=\"")
             .append("https://uat-us-cdn.obuy.com/image/gift-card-io8mxg.png.png")
             .append("\"/>\n")
         svgBuilder.append("</svg>")*/

        val svgBuilder = StringBuilder()
        svgBuilder
            .append("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=1.1")
            .append("\">\n")
        svgBuilder
            .append("  <image width=\"")
            .append(450)
            .append("\" height=\"")
            .append(250)
            .append("\" xlink:href=\"")
            .append("https://uat-us-cdn.obuy.com/image/gift-card-io8mxg.png.png")
            .append("\"/>\n")
        svgBuilder.append("</svg>")

        LogUtils.eTag("MainActivity", "svgBuilder $svgBuilder")

        //生成图片
        /*val file = File(
            getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
            "custorm.png"
        )
        val os = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os)
        os.flush()
        os.close()*/

        /*val inputStream = FileInputStream(file.path)
        val outputStream = ByteArrayOutputStream()


        val buf = byteArrayOf(1024.toByte())
        var bytesRead = 0
        while ((inputStream.read(buf).also { bytesRead = it }) > 0) {
            outputStream.write(buf, 0, bytesRead)
        }

        val byteArray = outputStream.toByteArray()
        val svgString = String(byteArray)
        val resultb = SVG.getFromString(svgString)
        LogUtils.eTag("MainActivity", "resultb $resultb")*/
    }

    suspend fun getUserInfo(): String {
        withContext(Dispatchers.IO) {
            delay(2000L)
        }
        return "BoyCoder"
    }

    suspend fun getFriendList(user: String): String {
        withContext(Dispatchers.IO) {
            delay(2000L)
        }
        return "Tom, Jack"
    }

    suspend fun getFeedList(list: String): String {
        withContext(Dispatchers.IO) {
            delay(2000L)
        }
        return "{FeedList..}"
    }

    private val formatter = DateTimeFormatter.ofPattern("HH:mm:ss")
    private fun String.log() = println(TAG + ": " + LocalTime.now().format(formatter) + ": $this \n")
//    private fun String.log() = println(LocalTime.now().format(formatter) + ": $this, Thread: " + Thread.currentThread().name)

}